package cn.com.fuhuitong.main.mine.ui.activity

import android.graphics.Color
import android.text.Editable
import android.widget.Toast
import androidx.lifecycle.Observer
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.mine.entity.AddressAddEntity
import cn.com.fuhuitong.main.mine.entity.AddressEntity
import cn.com.fuhuitong.main.mine.vm.AddressViewModel
import cn.com.fuhuitong.utils.JsonUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.blankj.utilcode.util.LogUtils
import com.contrarywind.interfaces.IPickerViewData
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Function4
import kotlinx.android.synthetic.main.activity_mine_address_edit.*
import razerdp.util.KeyboardUtils


@Route(path = ARouteConstance.ACTIVITY_URL_MINE_ADDRESS_EDIT)
class MineAddressEditActivity : ViewModeActivity<AddressViewModel>() {

    private val option: OptionsPickerView<IPickerViewData> by lazy {
        OptionsPickerBuilder(this,
            OnOptionsSelectListener { options1, options2, options3, _ ->
                viewModel.provinceList?.let {
                    val provinceEntity = it[options1]
                    val cityEntity = provinceEntity.cityList[options2]
                    val areaEntity = cityEntity.areaList[options3]
                    with(viewModel.selectProvince) {
                        provinceId = provinceEntity.provinceId
                        provinceName = provinceEntity.provinceName
                        cityId = cityEntity.cityId
                        cityName = cityEntity.cityName
                        areaId = areaEntity.id
                        areaName = areaEntity.areaName
                    }
                    edit_address_add_pca.text = buildString {
                        append(provinceEntity.provinceName)
                            .append(" ").append(cityEntity.cityName)
                            .append(" ").append(areaEntity.areaName)
                    }
                }
            }).build<IPickerViewData>()
    }

    private var addressEntity: AddressEntity? = null

    override fun viewModel(): AddressViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_mine_address_edit

    override fun initView() {

        image_address_edit_back.setOnClickListener {
            this.finish()
        }

        val observableAddName: Observable<CharSequence> =
            RxTextView.textChanges(edit_address_add_name)
        val observableAddPhone: Observable<CharSequence> =
            RxTextView.textChanges(edit_address_add_phone)
        val observableAddPca: Observable<CharSequence> =
            RxTextView.textChanges(edit_address_add_pca)
        val observableAddAddress: Observable<CharSequence> =
            RxTextView.textChanges(edit_address_add_address)

        val observable: Disposable = Observable.combineLatest(
            observableAddName, observableAddPhone, observableAddPca, observableAddAddress,
            Function4<CharSequence, CharSequence, CharSequence, CharSequence, Boolean> { t1, t2, t3, t4 ->
                t1.isNotEmpty() && t2.isNotEmpty() && t3.isNotEmpty() && t4.isNotEmpty()
            })
            .subscribe {
                text_address_add_submit.isEnabled = it
            }
        viewModel.dispose().add(observable)


        addressEntity = intent?.getSerializableExtra(AppConstance.BUNDLE_ADDRESS_ENTITY)
                as? AddressEntity
        addressEntity?.let {
            edit_address_add_name.text =
                Editable.Factory.getInstance().newEditable(it.contact_name)
            edit_address_add_phone.text =
                Editable.Factory.getInstance().newEditable(it.contact_mobile)
            edit_address_add_pca.text = Editable.Factory.getInstance().newEditable(
                "${it.province} ${it.city} ${it.area}"
            )
            edit_address_add_address.text =
                Editable.Factory.getInstance().newEditable(it.address)
            check_address_add_default.isChecked = it.is_default == 1
        }


        edit_address_add_pca.setOnClickListener {
            viewModel.provinceUIData?.let {
                if (KeyboardUtils.isOpen())
                    KeyboardUtils.close(this)
                option.setPicker(it.provinceUIList, it.cityUIList, it.areaUIList)
                option.show()
            }
        }

        text_address_add_submit.setOnClickListener {
            val type: Int = intent?.getIntExtra(AppConstance.BUNDLE_ADDRESS_TYPE, 0) ?: 0
            val address: List<String> = edit_address_add_pca.text.toString().split(" ")
            val entity = AddressAddEntity(
                address_id = addressEntity?.id ?: 0,
                contact_name = edit_address_add_name.text.toString(),
                contact_mobile = edit_address_add_phone.text.toString(),
                province = address[0],
                city = address[1],
                area = address[2],
                address = edit_address_add_address.text.toString(),
                is_default = if (check_address_add_default.isChecked) 1 else 0
            )
            LogUtils.e("${addressEntity?.id ?: 0}  " + JsonUtils.objectToString(entity))
            if (type == 1) {
                //修改地址
                viewModel.addressEdit(entity)
            } else {
                //添加地址
                viewModel.addressAdd(entity)
            }
        }
    }

    override fun initViewMode() {
        viewModel.getProvinceFromAssets()
        viewModel.baseDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            this.finish()
        })
    }

    override fun initData() {

    }
}